<template>
  <div class="student-center">
    <el-container>
      <el-header class="center-header">
        <h2>个人中心</h2>
      </el-header>
      
      <el-main class="center-main">
        <el-row :gutter="20">
          <!-- 个人信息卡片 -->
          <el-col :span="16">
            <el-card class="info-card">
              <template #header>
                <div class="card-header">
                  <span>个人信息</span>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="toggleEditMode"
                    :loading="saving"
                  >
                    {{ isEditMode ? '取消编辑' : '编辑信息' }}
                  </el-button>
                </div>
              </template>
              
              <!-- 个人信息展示组件 -->
              <PersonalInfoDisplay 
                v-if="!isEditMode"
                :student-info="studentInfo"
                :loading="loading"
              />
              
              <!-- 个人信息编辑组件 -->
              <PersonalInfoEdit
                v-else
                :student-info="studentInfo"
                :loading="saving"
                @save="handleSaveInfo"
                @cancel="toggleEditMode"
              />
            </el-card>
          </el-col>
          
          <!-- 侧边栏操作 -->
          <el-col :span="8">
            <!-- 头像上传卡片 -->
            <el-card class="avatar-card" style="margin-bottom: 20px;">
              <template #header>
                <span>头像设置</span>
              </template>
              <AvatarUpload
                :current-avatar="studentInfo.photo"
                :loading="saving"
                @upload-success="handleAvatarUpload"
              />
            </el-card>
            
            <!-- 密码修改卡片 -->
            <el-card class="password-card" style="margin-bottom: 20px;">
              <template #header>
                <span>密码管理</span>
              </template>
              <PasswordChange
                :user-id="studentInfo.userId"
                :username="studentInfo.studentId"
                :loading="saving"
                @change="handlePasswordChange"
              />
            </el-card>
            
            <!-- 退出登录 -->
            <el-card class="logout-card">
              <template #header>
                <span>账户操作</span>
              </template>
              <el-button 
                type="danger" 
                style="width: 100%;"
                @click="handleLogout"
              >
                退出登录
              </el-button>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStudentPortalStore } from '@/stores/studentPortalStore'
import { useUserStore } from '@/stores/user'
import PersonalInfoDisplay from './components/PersonalInfoDisplay.vue'
import PersonalInfoEdit from './components/PersonalInfoEdit.vue'
import PasswordChange from './components/PasswordChange.vue'
import AvatarUpload from './components/AvatarUpload.vue'

// 路由和状态管理
const router = useRouter()
const studentPortalStore = useStudentPortalStore()
const userStore = useUserStore()

// 响应式数据
const isEditMode = ref(false)

// 计算属性
const studentInfo = computed(() => studentPortalStore.studentInfo)
const loading = computed(() => studentPortalStore.loading)
const saving = computed(() => studentPortalStore.saving)

// 方法
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
}

const handleSaveInfo = async (updateData) => {
  try {
    const success = await studentPortalStore.updateStudentCompleteInfo(updateData)
    if (success) {
      isEditMode.value = false
      ElMessage.success('个人信息更新成功')
      // 重新获取最新的学生信息
      const userId = userStore.userInfo?.id || userStore.userInfo?.userId
      if (userId) {
        await studentPortalStore.fetchStudentInfo(userId)
      }
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  }
}

const handleAvatarUpload = async (avatarUrl) => {
  try {
    if (avatarUrl) {
      // 更新学生信息中的头像地址
      const currentInfo = { ...studentInfo.value }
      currentInfo.photo = avatarUrl
      
      // 确保数字字段有合理的默认值
      currentInfo.sex = parseInt(currentInfo.sex) || 1
      currentInfo.classId = parseInt(currentInfo.classId) || 1
      currentInfo.majorId = parseInt(currentInfo.majorId) || 1
      currentInfo.dormId = parseInt(currentInfo.dormId) || 1
      
      // 调用更新信息API保存新头像地址
      const success = await studentPortalStore.updateStudentCompleteInfo(currentInfo)
      if (success) {
        ElMessage.success('头像保存成功')
        // 重新获取最新的学生信息
        const userId = userStore.userInfo?.id || userStore.userInfo?.userId
        if (userId) {
          await studentPortalStore.fetchStudentInfo(userId)
        }
      } else {
        ElMessage.error('头像保存失败')
      }
    }
  } catch (error) {
    console.error('头像保存失败:', error)
    ElMessage.error('头像保存失败')
  }
}

const handlePasswordChange = async (passwordData) => {
  try {
    const success = await studentPortalStore.updatePassword(passwordData)
    if (success) {
      ElMessage.success('密码修改成功')
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error('密码修改失败')
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 清除用户状态
    userStore.logout()
    studentPortalStore.resetState()
    
    // 跳转到登录页
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch (error) {
    // 用户取消操作
  }
}

// 生命周期
onMounted(async () => {
  // 获取当前用户ID
  const userId = userStore.userInfo?.id || userStore.userInfo?.userId
  if (userId) {
    await studentPortalStore.fetchStudentInfo(userId)
  } else {
    ElMessage.error('用户信息获取失败，请重新登录')
    router.push('/login')
  }
})
</script>

<style scoped>
.student-center {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.center-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.center-header h2 {
  margin: 0;
  color: #303133;
}

.center-main {
  padding: 20px;
}

.info-card,
.avatar-card,
.password-card,
.logout-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: 600;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .center-main {
    padding: 10px;
  }
  
  .el-col {
    margin-bottom: 20px;
  }
}
</style>